# keywordbiff.awk v1.01 - 2010 Michael S. Sanders
# updates at: http://topcat.hypermart.net/index.html
# license: GPL3
#
# gawk program file parses email headers for keywords
# and if found performs an action based upon keywords
# the keyword list is located in an external file and
# takes the format of a single word or phrase per line

BEGIN {

USER    = "caesar@empire.org"          # pop3 login
PASS    = "tacobell"                   # pop3 password
POP3    = "pop.empire.org"             # pop3 server
KEYFILE = "keywords.txt"               # file with keyowrds

# end user configuration

KEYCOUNT = GetKeyWords(KEYFILE)        # number of elements in keyfile
SERVER   = "/inet/tcp/0/" POP3 "/pop3" # inet string

if (KEYCOUNT < 1 ) {                   # exit if keycount < 1
    print "no data..."
    exit
}

SERVER |& getline                      # attempt to open socket/get HELLO
if ($1 != "+OK") {exit}                # houston, we've got a problem...

SendPOPMsg("user " USER)               # send pop3 login
SendPOPMsg("pass " PASS)               # send pop3 password
split(SendPOPMsg("stat"), foo, / /)    # get number of emails

if (foo[2] > 0) {                      # acquire headers
    SendPOPMsg("top 1 0")
    RS = "\r\n\\.\r\n"
        for (x = 1; x <= foo[2]; x++) {
            var = var SendPOPMsg("top " x " 0")
        }
}

SendPOPMsg("quit")                     # tell pop3 server we quit!
close(SERVER)                          # close socket

if (foo[2] > 0) {                      # parse headers
    ProcPOPMsg(tolower(var))
}

}

# ---------------------------------------------------------------------------

function SendPOPMsg(msg) {

print msg |& SERVER
SERVER |& getline

return $0

}

# ---------------------------------------------------------------------------

function ProcPOPMsg(str,    x) {

for (x = 1; x <= KEYCOUNT; x++) {
    if (index(str, keyword[x]) > 0) {
        print "You've got mail..."                  # output message
        # system("xmessage \"You've got mail...\"") # show dialog
        # system("play -q notify.wav")              # play wav file
        # system("shutdown -r")                     # reboot computer
        # system("shutdown -h")                     # turn off computer
        exit
    }
}

}

# ---------------------------------------------------------------------------

function GetKeyWords(file,    tmp, q) {

while ((getline tmp < file) > 0) {
    if (length(tmp)) {keyword[++q] = tolower(tmp)}
}
close(file)

return q

}

# eof
